package com.group.nepg.controller;
import com.group.common.users.NEPGUser;
import com.group.common.utils.MyUtils;
import com.group.nepg.entity.DataDetectionDataLoader;
import com.group.neps.entity.RowAqiData;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import java.util.ArrayList;
import java.util.List;

// 数据检测控制器  接受系统管理员派发的任务去实地检测，填写数据

public class DataDetectionController {
    @FXML private Label username;              // 显示当前登录用户
    @FXML private Button detectButton;         // 导航到测量页面的按钮
    @FXML private Button backButton;           // 返回登录页面按钮
    @FXML private TableView<DataDetectionDataLoader> feedbackTableView; // 反馈信息表格
    @FXML private TableColumn<DataDetectionDataLoader, Integer> idColumn; // ID列
    @FXML private TableColumn<DataDetectionDataLoader, String> userColumn; // 用户名列
    @FXML private TableColumn<DataDetectionDataLoader, String> provinceColumn; // 省份列
    @FXML private TableColumn<DataDetectionDataLoader, String> cityColumn; // 城市列
    @FXML private TableColumn<DataDetectionDataLoader, String> addressColumn; // 地址列
    @FXML private TableColumn<DataDetectionDataLoader, String> levelColumn; // 空气质量等级列
    @FXML private TableColumn<DataDetectionDataLoader, String> timeColumn; // 时间列

    private static NEPGUser user; // 静态用户对象，存储当前登录用户信息
    private static boolean isCommit = false;
    private static RowAqiData selectedRowAqiData =  null;
    private static ArrayList<RowAqiData> dataList = MyUtils.readFileToArrayList("group/data/row_aqi_data_arraylist.dat");

    private ObservableList<DataDetectionDataLoader> tableData = FXCollections.observableArrayList(); //

    // 获取当前登录用户
    public static NEPGUser getUser() {
        return user;
    }

    // 设置当前登录用户
    public static void setUser(NEPGUser user) {
        DataDetectionController.user = user;
    }

    public static boolean isIsCommit() {
        return isCommit;
    }

    public static void setIsCommit(boolean isCommit) {
        DataDetectionController.isCommit = isCommit;
    }

    //给页面设置背景图片

    @FXML private ImageView imageView;
    @FXML private AnchorPane root;
    @FXML
    public void initializeImage() {
        try {

            Image image = new Image(getClass().getResourceAsStream("../image/grid.png"));
            imageView.setImage(image);
            imageView.fitWidthProperty().bind(root.widthProperty());
            imageView.fitHeightProperty().bind(root.heightProperty());
            imageView.setPreserveRatio(false);
            imageView.setSmooth(true);
        } catch (Exception e) {
            System.err.println("加载图片失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


     //初始化方法

    public void initialize() {
        if (isCommit) {
            if (selectedRowAqiData != null) {
                dataList.remove(selectedRowAqiData);
                MyUtils.writeArrayListToFile("group/data/row_aqi_data_arraylist.dat", dataList);
            }
            isCommit = false;
        }

        // 设置表格
        setupTableColumns();

        // 设置表格选择模式为单选
        feedbackTableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        loadData();

        // 初始化图片
        initializeImage();
    }


     //设置表格列
     //将表格列与DataDetectionDataLoader类的属性进行绑定

    private void setupTableColumns() {
        idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
        userColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        provinceColumn.setCellValueFactory(new PropertyValueFactory<>("provinceName"));
        cityColumn.setCellValueFactory(new PropertyValueFactory<>("cityName"));
        addressColumn.setCellValueFactory(new PropertyValueFactory<>("address"));
        levelColumn.setCellValueFactory(new PropertyValueFactory<>("aqiLevel"));
        timeColumn.setCellValueFactory(new PropertyValueFactory<>("time"));
    }


     //从文件加载数据并更新表格

    private void loadData() {
        new Thread(() -> {
            try {
                // 更新用户名显示
                username.setText("网格员：" + user.getUsername());

                // 检查数据是否存在
                if (dataList == null || dataList.isEmpty()) {
                    System.out.println("没有数据可加载");
                    // 在JavaFX应用线程中更新UI
                    Platform.runLater(() -> feedbackTableView.setPlaceholder(new Label("暂无数据")));
                    return;
                }

                // 构建数据加载器列表并自动编号
                List<DataDetectionDataLoader> loaderList = new ArrayList<>();
                for (int i = 0; i < dataList.size(); i++) {
                    loaderList.add(new DataDetectionDataLoader(i + 1, dataList.get(i)));
                }

                // 在JavaFX应用线程中更新表格数据
                Platform.runLater(() -> {
                    tableData.setAll(loaderList);
                    feedbackTableView.setItems(tableData);
                });

            } catch (Exception e) {
                e.printStackTrace();
                // 在JavaFX应用线程中显示错误提示
                Platform.runLater(() ->
                        MyUtils.showAlert("错误", "数据加载失败", "无法从文件加载数据，请检查文件路径或格式。", Alert.AlertType.ERROR)
                );
            }
        }).start();
    }

    //通过鼠标直接点击事件去检测
    //单击表格行时，将选中的数据传递给测量控制器

    @FXML
    private void handleRowClick(MouseEvent event) {
        // 检查是否为单次点击且有选中项
        if (event.getClickCount() == 1 && !feedbackTableView.getSelectionModel().isEmpty()) {
            DataDetectionDataLoader selected = feedbackTableView.getSelectionModel().getSelectedItem();
            MeasurementController.setSelectedRowAqiData(selected.getRowAqiData());
            selectedRowAqiData = selected.getRowAqiData();
        }
    }


     // 检查是否已选择数据

    @FXML
    public void toMeasure(ActionEvent event) {
        // 检查是否选择了数据
        if (feedbackTableView.getSelectionModel().isEmpty()) {
            MyUtils.showAlert("提示", "请先选择一条反馈数据", "请在表格中选择一条公众反馈数据", Alert.AlertType.INFORMATION);
            return;
        }

        // 导航到测量数据页面
        MyUtils.navigateToView(event, "group/nepg/view/MeasurementView.fxml");
    }



     //清除当前用户信息并导航回登录页面

    @FXML
    private void backToLogin(ActionEvent event) {MyUtils.navigateToView(event, "group/nepg/view/UserLoginView.fxml");
    }
}